/**
 *
 */
package com.zhuoyue.elmt.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eit.eitsite.common.utils.IdGen;
import com.eit.eitsite.modules.sys.service.DictService;
import com.eit.eitsite.modules.sys.utils.DictUtils;
import com.eit.eitsite.modules.sys.utils.UserUtils;
import com.zhuoyue.elmt.Constants;
import com.zhuoyue.elmt.UserFilterUtils;
import com.zhuoyue.elmt.data.ResultData;
import com.zhuoyue.elmt.entity.FailureReport;
import com.zhuoyue.elmt.entity.MaintenanceRecordSz;
import com.zhuoyue.elmt.entity.MaintenanceStaff;
import com.zhuoyue.elmt.service.MaintenanceStaffDeviceService;
import com.zhuoyue.elmt.service.MaintenanceStaffService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.eit.eitsite.common.config.Global;
import com.eit.eitsite.common.persistence.Page;
import com.eit.eitsite.common.web.BaseController;
import com.eit.eitsite.common.utils.StringUtils;
import com.zhuoyue.elmt.service.FailureReportService;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 电梯故障报告Controller
 *
 * @author chenhao
 * @version 2016-09-07
 */
@Controller
@RequestMapping(value = "${adminPath}/elmt/failureReport")
public class FailureReportController extends BaseController {

    @Autowired
    private FailureReportService failureReportService;

    @Autowired
    private MaintenanceStaffDeviceService maintenanceStaffDeviceService;

    @Autowired
    private MaintenanceStaffService maintenanceStaffService;

    @ModelAttribute
    public FailureReport get(@RequestParam(required = false) String formId) {
        FailureReport entity = null;
        if (StringUtils.isNotBlank(formId)) {
            entity = failureReportService.get(formId);
        }
        if (entity == null) {
            entity = new FailureReport();
        }
        return entity;
    }

    /**
     * 根据设备代码查询当前处理的故障报告
     *
     * @param str1
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getFailureReportByDevcieCode/{str1}")
    public String getFailureReportByDevcieCode(@PathVariable String str1, HttpServletResponse response) {
        ResultData<List<FailureReport>> resultData = new ResultData();
        List<FailureReport> list = new ArrayList();
        try {
            System.out.println("根据设备代码查询当前处理的故障报告 ===========================================>>>>>>>>>>>>>>");
            HashMap params = new HashMap();
            params.put("deviceCode", str1);
            params.put("createdBy", UserUtils.getUser().getLoginName());
            FailureReport record = failureReportService.getFailureReportByDeviceCode(params);
            if (record != null) {
                resultData.setCode("SUCC");
                resultData.setMessage("SUCCESS");
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("没有查询到符合条件的电梯故障报告！");
            }
            list.add(record);
            resultData.setList(list);
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("电梯故障报告查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    /**
     * 查询单条故障报告
     *
     * @param str1
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getFailureReportInfo/{str1}")
    public String getFailureReportInfo(@PathVariable String str1, HttpServletResponse response) {
        ResultData<List<FailureReport>> resultData = new ResultData();
        List<FailureReport> list = new ArrayList();
        try {
            System.out.println("查询单条故障报告 ===========================================>>>>>>>>>>>>>>");
            FailureReport record = failureReportService.get(str1);
            if (record != null) {
                // 拿到设备对应的维保人员列表
                MaintenanceStaff qryMaintenanceStaff = new MaintenanceStaff();
                qryMaintenanceStaff.setWbdwdm(UserUtils.getUser().getCompany().getCode());
                qryMaintenanceStaff.setDeviceCode(record.getDeviceCode());

                List<MaintenanceStaff> staffList = maintenanceStaffService.findDeviceMainStaffList(qryMaintenanceStaff);
                record.setStaffList(staffList);

                resultData.setCode("SUCC");
                resultData.setMessage("SUCCESS");
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("没有查询到符合条件的电梯故障报告！");
            }
            list.add(record);
            resultData.setList(list);
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("电梯故障报告查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    /**
     * 查询多条故障报告
     *
     * @param failureReport
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/findFailureReportInfo")
    public String findFailureReportInfo(FailureReport failureReport, HttpServletRequest request, HttpServletResponse response) {
        ResultData<List<FailureReport>> resultData = new ResultData();
        try {
            System.out.println("查询多条故障报告 ===========================================>>>>>>>>>>>>>>");

            // 设置维保人员和维保单位代码过滤条件
            // failureReport.setCreatedBy(UserFilterUtils.getMainStaff());
            failureReport.setMaintenUnitCode(UserFilterUtils.getMainUnitCode());

            Page<FailureReport> page = failureReportService.findPage(new Page<FailureReport>(request, response), failureReport);
            if (null != page) {
                resultData.setList(page.getList());
            }
            resultData.setCode("SUCC");
            resultData.setMessage("");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("电梯故障报告查询出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/saveFailureReportInfo")
    public String saveFailureReportInfo(FailureReport failureReport, String faultNo, Model model, HttpServletResponse response) {
        ResultData<List<FailureReport>> resultData = new ResultData();
        List<FailureReport> list = new ArrayList();
        try {
            System.out.println("增加电梯故障报告 ===========================================>>>>>>>>>>>>>>");
            if (!beanValidator(model, failureReport)) {
                return form(failureReport, model);
            }
            failureReport.setMaintenanceStaff(UserUtils.getUser().getLoginName());
            failureReport.setCreatedBy(UserUtils.getUser().getLoginName());
            failureReport.setLastUpdateBy(UserUtils.getUser().getLoginName());
            failureReport.setMaintenUnitCode(UserUtils.getUser().getCompany().getCode());

            if (StringUtils.isNotEmpty(faultNo)) {
                failureReport.setSourceNo(faultNo);
                failureReport.setSourceType(Constants.FailureReport.SOURCE_TYPE_FAULT);
            }

            boolean isSave = false;
            if (StringUtils.isEmpty(failureReport.getFormId())) {
                isSave = true;
            }

            failureReportService.save(failureReport);
            System.out.println("wbFailureReport.getRecordId() ================>>>>>>>>>>>>>> " + failureReport.getFormId());

            if (isSave) {
                failureReport = failureReportService.get(failureReport.getFormId());
            }

            //增加返回model
            list.add(failureReport);
            resultData.setList(list);

            resultData.setFormId(failureReport.getFormId());
            resultData.setCode("SUCC");
            resultData.setMessage("增加电梯故障报告成功");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("增加电梯故障报告出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/updateFailureReportInfo")
    public String updateFailureReportInfo(FailureReport failureReport, Model model, HttpServletResponse response) {
        ResultData<List<FailureReport>> resultData = new ResultData();
        List<FailureReport> list = new ArrayList();
        try {
            System.out.println("更新电梯故障报告 ===========================================>>>>>>>>>>>>>>");
            if (!beanValidator(model, failureReport)) {
                return form(failureReport, model);
            }
            if (StringUtils.isNotEmpty(failureReport.getFormId())) {
                failureReport.setLastUpdateBy(UserUtils.getUser().getLoginName());
                failureReportService.update(failureReport);

                //增加返回model
                list.add(failureReport);
                resultData.setList(list);

                resultData.setCode("SUCC");
                resultData.setMessage("更新电梯故障报告成功");
            }
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("更新电梯故障报告出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequestMapping(method = RequestMethod.POST, value = "/deleteFailureReportInfo")
    public String deleteFailureReportInfo(FailureReport failureReport, Model model, HttpServletResponse response) {
        ResultData<List<FailureReport>> resultData = new ResultData();
        List<FailureReport> list = new ArrayList();
        try {
            System.out.println("删除电梯故障报告 ===========================================>>>>>>>>>>>>>>");
            if (!beanValidator(model, failureReport)) {
                return form(failureReport, model);
            }
            failureReportService.deleteFailureReportInfo(failureReport);

            resultData.setFormId(failureReport.getFormId());
            resultData.setCode("SUCC");
            resultData.setMessage("删除电梯故障报告成功");
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("删除电梯故障报告出现异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }

    @RequiresPermissions("elmt:failureReport:view")
    @RequestMapping(value = {"list", ""})
    public String list(FailureReport failureReport, HttpServletRequest request, HttpServletResponse response, Model model) {
        // 设置维保人员和维保单位代码过滤条件
        // failureReport.setCreatedBy(UserFilterUtils.getMainStaff());
        failureReport.setMaintenUnitCode(UserFilterUtils.getMainUnitCode());

        Page<FailureReport> page = failureReportService.findPage(new Page<FailureReport>(request, response), failureReport);
        model.addAttribute("page", page);
        return "zhuoyue/elmt/failureReportList";
    }

    @RequiresPermissions("elmt:failureReport:view")
    @RequestMapping(value = "form")
    public String form(FailureReport failureReport, Model model) {
        model.addAttribute("failureReport", failureReport);

        // 故障状态
        model.addAttribute("allFailureStatus", DictUtils.getDictList("FAILURE_STATUS"));

        // 处理状态
        model.addAttribute("allFailurePrecessStatus", DictUtils.getDictList("FAILURE_PROCESS_STATUS"));

        String failureStatus = failureReport.getFailureStatus();
        String processStatus = failureReport.getProcessStatus();

        List failureStatusList = new ArrayList();
        if(StringUtils.isNotEmpty(failureStatus)) {
            String[] failureStatusArray = failureStatus.split(",");
            for (int i = 0; i < failureStatusArray.length; i++) {
                failureStatusList.add(failureStatusArray[i]);
            }
        }
        failureReport.setFailureStatusList(failureStatusList);

        List processStatusList = new ArrayList();
        if(StringUtils.isNotEmpty(processStatus)) {
            String[] processStatusArray = processStatus.split(",");
            for (int i = 0; i < processStatusArray.length; i++) {
                processStatusList.add(processStatusArray[i]);
            }
        }
        failureReport.setProcessStatusList(processStatusList);

        return "zhuoyue/elmt/failureReportForm";
    }

    @RequiresPermissions("elmt:failureReport:edit")
    @RequestMapping(value = "save")
    public String save(FailureReport failureReport, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, failureReport)) {
            return form(failureReport, model);
        }
        failureReportService.save(failureReport);
        addMessage(redirectAttributes, "保存故障报告成功");
        return "redirect:" + Global.getAdminPath() + "/elmt/failureReport/?repage";
    }

    @RequiresPermissions("elmt:failureReport:edit")
    @RequestMapping(value = "delete")
    public String delete(FailureReport failureReport, RedirectAttributes redirectAttributes) {
        failureReportService.delete(failureReport);
        addMessage(redirectAttributes, "删除故障报告成功");
        return "redirect:" + Global.getAdminPath() + "/elmt/failureReport/?repage";
    }

    private void uploadMtFile(FailureReport failureReport, HttpServletRequest request, ResultData<List<MaintenanceRecordSz>> resultData) {
        // 上传文件
        if (request instanceof MultipartHttpServletRequest) {
            MultipartFile safety_officer_photo = ((MultipartHttpServletRequest) request).getFile("safety_officer_photo");
            if (safety_officer_photo != null && !safety_officer_photo.isEmpty()) {
                String relaPath = Global.USERFILES_BASE_URL + "frsign/";
                String realPath = Global.getUserfilesBaseDir() + relaPath;
                String fileName = safety_officer_photo.getOriginalFilename();
                String rname = IdGen.uuid() + fileName.substring(fileName.lastIndexOf("."));
                File targetFile = new File(realPath, rname);
                // 目录不存在，则创建目录
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                // 保存
                try {
                    safety_officer_photo.transferTo(targetFile);
                    String filePath = request.getContextPath() + relaPath + rname;
                    failureReport.setSafetyOfficerPhoto(filePath);
                } catch (Exception e) {
                    resultData.setCode("FAIL");
                    resultData.setMessage("管理人员签名上传失败");
                    e.printStackTrace();
                }
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("管理人员签名上传失败");
            }

            MultipartFile maintenance_staff1_photo = ((MultipartHttpServletRequest) request).getFile("maintenance_staff1_photo");
            if (maintenance_staff1_photo != null && !maintenance_staff1_photo.isEmpty()) {
                String relaPath = Global.USERFILES_BASE_URL + "frsign/";
                String realPath = Global.getUserfilesBaseDir() + relaPath;
                String fileName = maintenance_staff1_photo.getOriginalFilename();
                String rname = IdGen.uuid() + fileName.substring(fileName.lastIndexOf("."));
                File targetFile = new File(realPath, rname);
                // 目录不存在，则创建目录
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                // 保存
                try {
                    maintenance_staff1_photo.transferTo(targetFile);
                    String filePath = request.getContextPath() + relaPath + rname;
                    failureReport.setMaintenanceStaff1Photo(filePath);
                } catch (Exception e) {
                    resultData.setCode("FAIL");
                    resultData.setMessage("维保人员1签名上传失败");
                    e.printStackTrace();
                }
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("维保人员1签名上传失败");
            }

            MultipartFile maintenance_staff2_photo = ((MultipartHttpServletRequest) request).getFile("maintenance_staff2_photo");
            if (maintenance_staff2_photo != null && !maintenance_staff2_photo.isEmpty()) {
                String relaPath = Global.USERFILES_BASE_URL + "frsign/";
                String realPath = Global.getUserfilesBaseDir() + relaPath;
                String fileName = maintenance_staff2_photo.getOriginalFilename();
                String rname = IdGen.uuid() + fileName.substring(fileName.lastIndexOf("."));
                File targetFile = new File(realPath, rname);
                // 目录不存在，则创建目录
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                // 保存
                try {
                    maintenance_staff2_photo.transferTo(targetFile);
                    String filePath = request.getContextPath() + relaPath + rname;
                    failureReport.setMaintenanceStaff2Photo(filePath);
                } catch (Exception e) {
                    resultData.setCode("FAIL");
                    resultData.setMessage("维保人员2签名上传失败");
                    e.printStackTrace();
                }
            } else {
                resultData.setCode("FAIL");
                resultData.setMessage("维保人员2签名上传失败");
            }
        }
    }

}